package com.kbatis.utils;


import com.kbatis.config.Configuration;
import com.kbatis.sqlsession.SqlSession;
import com.kbatis.io.Resources;
import com.kbatis.sqlsession.SqlSessionFactory;
import com.kbatis.sqlsession.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;

/**
 * ClassName: DataSourceUtil
 * Description:
 *
 * @author 小黄
 * date: 2019/11/19 17:25
 */
public class DataSourceUtil {

    /**
     * 用于获取一个连接
     * @param cfg
     * @return
     */
    public static Connection getConnection(Configuration cfg){
        try {
            Class.forName(cfg.getDriver());
            return DriverManager.getConnection(cfg.getUrl(), cfg.getUsername(), cfg.getPassword());
        }catch(Exception e){
            throw new RuntimeException(e);
        }
    }

    public static SqlSession getSqlSession(String location) {
        InputStream inputStream = Resources.getResourcesAsStream(location);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        return sqlSession;
    }
}